<?php

function document_instance_add_page($template_id) {
    drupal_add_css('sites/all/themes/nonghua/css/document_template.css');
    return drupal_get_form('document_instance_edit_form', $template_id);
}

function document_instance_edit_page($template_id, $instance_id) {
    drupal_add_css('sites/all/themes/nonghua/css/document_template.css');
    return drupal_get_form('document_instance_edit_form', $template_id, $instance_id);
}

function document_instance_edit_form($form, &$form_state)
{
    $template_id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : '';
    $instance_id = isset($form_state['build_info']['args'][1]) ? $form_state['build_info']['args'][1] : '';

    $form['template_id'] = array('#type' => 'hidden', '#default_value' => $template_id);
    $form['instance_id'] = array('#type' => 'hidden', '#default_value' => $instance_id);

    // 取得模板form 元素
    $form_json = '';
    $collection_name = '';
    $result = db_select('document_template', 'dt')
        ->fields('dt', array('collection', 'form_json'))
        ->condition('document_template_id', $template_id, '=')
        ->execute();
    if ($result->rowCount() == 0) {
        drupal_set_message(t('文档模板不存在！'), 'status', FALSE);
        drupal_goto('document_instance/list');
    }
    foreach ($result as $record) {
        $form_json = $record->form_json;
        $collection_name = $record->collection;
    }
    $form['collection_name'] = array('#type' => 'hidden', '#default_value' => $collection_name);

    // 取得object id
    $object_id = '';
    $addr_id = '';
    $author_uid = '';
    if (!empty($instance_id)) {
        $instance = db_select('document_instance', 'mi')
            ->fields('mi', array(
                'object_id',
                'addr_id',
                'author_uid'
            ))
            ->condition('document_template_id', $template_id, '=')
            ->condition('document_instance_id', $instance_id, '=')
            ->execute();
        if ($instance->rowCount() == 0) {
            drupal_set_message(t('文档不存在！'), 'status', FALSE);
            drupal_goto('document_instance/list');
        }
        foreach ($instance as $record) {
            $object_id = $record->object_id;
            $addr_id = $record->addr_id;
            $author_uid = $record->author_uid;
        }
        $form['object_id'] = array('#type' => 'hidden', '#default_value' => $object_id);
    }

    // 取得公有元素
    $form = array_merge($form, _get_basic_elements_for_template($form, $form_state, $author_uid, $addr_id));

    // 插入值到HTML中
    $form['template'] = array(
//        '#type' => 'fieldset',
//        '#title' => '表格内容',
//        '#collapsible' => TRUE,
//        '#collapsed' => FALSE,
    );
    if (!empty($object_id)) {
        $form['template']['content'] = _add_form_elements_values($collection_name, $object_id, $form_json);
    } else {
        $form['template']['content'] = drupal_json_decode($form_json);
    }

    // 添加submit按钮
    global $user;
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => empty($instance_id) ? '添加' : '修改',
        '#access' => nonghua_user_access('document_instance','edit',$instance_id,$author_uid,0),
        '#validate' => array("check_addr_selected"),
    );

    return $form;
}

function document_instance_edit_form_submit($form, &$form_state)
{
    global $user;

    $template_id = $form_state['values']['template_id'];
    $collection_name = $form_state['values']['collection_name'];
    $object_id = !empty($form_state['values']['object_id'])? $form_state['values']['object_id'] : ($user->uid . '_' . time());
    $insert_or_update = !empty($form_state['values']['object_id'])? "update" : "insert";

    $object_content = _generate_mongo_object($form, $form_state, $object_id);
    $result = false;
    try {
//        $conn = _connection_mongodb();
//        $db = $conn->junong;
//        $collection_object = $db->$collection_name;
//        $result = ($insert_or_update == "insert") ?
//            (bool)$collection_object->insert($object_content) :
//            (bool)$collection_object->update(array("_id" => $object_id), $object_content);
//
//        $conn->close();


        $manager = _connection_mongodb();
        if($insert_or_update == "insert"){
            // 插入数据
            $bulk = new MongoDB\Driver\BulkWrite;
            $bulk->insert($object_content);
            $result= $manager->executeBulkWrite('junong.'.$collection_name, $bulk);
        }else{
            $bulk = new MongoDB\Driver\BulkWrite;
            $bulk->update(
                ['_id' => $object_id.''],
                ['$set' => $object_content],
                ['multi' => false, 'upsert' => false]
            );
            $writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
            $result = $manager->executeBulkWrite('junong.'.$collection_name, $bulk, $writeConcern);
        }



    } catch (Exception $e) {
        drupal_set_message(t('mongodb插入错误'), 'status', FALSE);
    }
    if ($result) {
        if ($insert_or_update == "insert") {
            db_insert('document_instance')
                ->fields(array(
                    'document_template_id' => $template_id,
                    'object_id' => $object_id,
                    'addr_id' => $address =  _get_address_id_from_autocomplete_select($form_state),
                    'author_uid' => $user->uid,
                    'timestamp' => time(),
                ))
                ->execute();
            drupal_set_message(t('文档提交成功'), 'status', FALSE);
        } else {
            db_update('document_instance')
                ->fields(array(
                    'addr_id' => _get_address_id($form_state),
                    'timestamp' => time(),
                ))
                ->condition('document_template_id', $template_id, '=')
                ->condition('author_uid', $user->uid, '=')
                ->condition('object_id', $object_id, '=')
                ->execute();
            drupal_set_message(t('文档更新成功'), 'status', FALSE);
        }
    }
}

function _get_all_valid_types()
{
    $result = db_query("select type from document_type");
    $types = [];
    foreach ($result as $row) {
        $types[] = $row->type;
    }

    return $types;
}

function _generate_mongo_object($form, $form_state, $object_id)
{
    $insert_obj = [];
    $insert_obj["_id"] = $object_id;

    $types = _get_all_valid_types();
    $insert_obj = array_merge($insert_obj, _generate_mongo_object_recursively($form['template']['content'], $form_state, $types));

    return $insert_obj;
}

function _generate_mongo_object_recursively($part_form, $form_state, $types)
{
    $object = [];
    foreach ($part_form as $key => $value) {
        if (substr($key, 0, 1) != '#') {
            if (isset($value['#type'])) {
                if (in_array($value['#type'], $types)) {
                    if ($value['#type'] != 'managed_file') {
                        $object[$key]['#type'] = $value['#type'];
                        $object[$key]['#value'] = $form_state['values'][$key];
                    } else {
                        if ($form_state['values'][$key] != 0) {
                            $file = file_load($form_state['values'][$key]);
                            $file->status = FILE_STATUS_PERMANENT;
                            file_save($file);
                            file_usage_add($file, 'document_instance', 'attachment', time());
                        } else {
                            if (isset($part_form[$key]['#default_value'])) {
                                $file = file_load($part_form[$key]['#default_value']);
                                if ($file) {
                                    file_delete($file);
                                    file_usage_delete($file, 'document_instance');
                                }
                            }
                        }
                        $object[$key]['#type'] = $value['#type'];
                        $object[$key]['#value'] = $form_state['values'][$key];
                    }
                }
            } else {
                $object[$key] = _generate_mongo_object_recursively($value, $form_state, $types);
            }
        }
    }
    return $object;
}

function _get_basic_elements_for_template($form, &$form_state, $author_uid, $addr_id)
{
    global $user;

    $subform['inputer'] = array(
        "#type" => "textfield",
        "#title" => "录入者",
        "#size" => 4,
        "#maxlength" => 4,
        "#required" => true,
        "#default_value" => _get_user_info($author_uid)['name'],
        "#disabled" => true,
    );
    $subform['address_fuzzy'] = _insert_address_autocomplete($form, $form_state,isset($record) && !empty($record)?$record->addr_id:'');
    $subform['address'] = _insert_address_selection_form($form, $form_state, 'address', 5, FALSE, $addr_id, '地点', '');

    return $subform;
}

function _add_form_elements_values($collection_name, $object_id, $form_json)
{
    try {
        $manager = _connection_mongodb();
//        $db = $conn->junong;
//        $collection_object = $db->$collection_name;
//        $mongo_object = $collection_object->findOne(array('_id' => $object_id));
//        $conn->close();
        $filter = ['_id' => ['$eq' => $object_id.'']];


// 查询数据
        $query = new MongoDB\Driver\Query($filter, []);
        $cursor = $manager->executeQuery('junong.'.$collection_name, $query);
        $form_object = drupal_json_decode($form_json);
        foreach ($cursor as $mongo_object) {
            $mongo_array =  json_decode( json_encode( $mongo_object),true);
            _add_form_element_values_recursively($mongo_array, $form_object);
        }

        return $form_object ;
    } catch (Exception $e) {
        drupal_set_message(t('mongodb读取错误'), 'status', FALSE);
    }
}

function _add_form_element_values_recursively($part_mongo_object, &$part_form_object)
{
    foreach ($part_mongo_object as $key => $value) {
        if (isset($part_form_object[$key])) {
            if (isset($part_form_object[$key]['#type']) && $part_form_object[$key]['#type'] == $value['#type']) {
                $part_form_object[$key]['#default_value'] = $value['#value'];
            } else {
                _add_form_element_values_recursively($value, $part_form_object[$key]);
            }
        }
    }
}

function document_instance_add_page_title($template_id)
{
    return '添加' . db_query("SELECT title from document_template where document_template_id = :template_id", array(':template_id' => $template_id))->fetchField();
}

function document_instance_edit_page_title($template_id, $instance_id)
{
    $result = db_query("SELECT dt.title, di.author_uid from document_template dt join document_instance di
                            on dt.document_template_id = di.document_template_id
                            where di.document_template_id = :template_id and di.document_instance_id = :instance_id",
                array(':template_id' => $template_id, ':instance_id' => $instance_id));
    $title = '';
    $author_uid = '';
    foreach ($result as $row) {
        $title = $row->title;
        $author_uid = $row->author_uid;
    }
    return $title;
}

function check_addr_selected($form, &$form_state)
{
    _address_element_validate($form_state);
}